<template>
	<comRoot>
		<template #page>
			<image v-if="commonConfigs && commonConfigs.domainFrontFileLink" :src="`${commonConfigs.domainFrontFileLink}/files/images/page-bg.png`" class="bg" />
			
			<comDetailNavigateBack title="我的优惠券" />

			<comScrollTab v-model="tabCurrentIndex" :list="tabAreaList">
				<scroll-view scroll-y @scrolltolower="scrolltolower" :style="{height: 'calc(100vh - ' + commonNavHeight + ' - 120rpx)'}">
					<view class="coupon-content relative flex-justify-content-between" v-if="tabAreaList[tabCurrentIndex].type === 1">
						<view class="coupon-input relative">
							<input class="relative" type="text" v-model="uniq" style="width: 100%;height: 100%;z-index: 10;" placeholder="请输入优惠券口令"
								placeholder-style="font-size: 24rpx;color: #8F4FFF;" />
							<image class="bg"
								:src="`${commonConfigs.domainFrontFileLink}/files/images/coupons/coupon-input-bg.png`"
								mode=""></image>
						</view>
						<!-- 领取 -->
						<view class="coupon-receive-btn relative" @click="setCouponReceiveFun">
							<image class="bg" :src="`${commonConfigs.domainFrontFileLink}/files/images/coupons/receive-btn.png`" mode=""></image>
						</view>
					</view>

					<view class="coupon-box-top flex-align-items-center flex-justify-content-between" v-if="tabAreaList[tabCurrentIndex].type === 3">
						<view class="text">当前可领取<text style="color: #63FFF7;font-size: 38rpx;">{{ resLists.length || 0 }}</text>张</view>
						<!-- 一键领取 -->
						<view class="box-top-btn" v-if="commonConfigs && commonConfigs.domainFrontFileLink"
							:style="{
								'background-image': `url(${commonConfigs.domainFrontFileLink}/files/images/coupons/all-receive-btn.png)`,
								'width': '160rpx',
								'height': '60rpx',
							}"
							@click="setAllReceiveFun">
						</view>
					</view>
					<view v-if="resLists && resLists.length">
						<comCouponList :resLists="resLists" :tabCurrentIndex="tabAreaList[tabCurrentIndex].type" @setClickRuleFun="setClickRuleFun" @putUseFun="putUseFun" @setChangeFun="setChangeFun" />
						<comLoadMore :loading="loading" :showLoadendTxt="showLoadendTxt" class="loadmore-txt"></comLoadMore>
					</view>
					<comEmptyData v-else></comEmptyData>
				</scroll-view>
			</comScrollTab>

			<!-- 兑换弹框 -->
			<comOperCouponPopup v-model="isShowCouponPopup" height="466rpx" 
				:titleSrc="
					tabAreaList[tabCurrentIndex].type === 0 
					? `${commonConfigs.domainFrontFileLink}/files/images/coupons/coupon-exchange-title.png` 
					: `${commonConfigs.domainFrontFileLink}/files/images/coupons/coupon-use-path-title.png`">
				<view 
					class="font-hanserif-bold tip-view-text"
					style="text-align: center;white-space: nowrap;"
					v-if="tabAreaList[tabCurrentIndex].type === 0">是否消耗{{ couponInfo.points }}积分兑换{{ couponInfo.discount }}元优惠券?</view>
				<view class="coupon-view flex relative" v-if="commonConfigs && commonConfigs.domainFrontFileLink"
					:style="{'background-image': `url(${commonConfigs.domainFrontFileLink}/files/images/coupons/coupon-bg.png)`}">
					
					<view class="coupon-view-left">
						<view>{{ couponInfo.titile }}</view>
						<view class="view-left-sub-title">{{ couponInfo.subtitile }}</view>
						<view class="view-left-bottom flex">
							<view style="white-space: nowrap;">到期时间：{{ couponInfo.end_time }}</view>
							<view style="white-space: nowrap;" class="coupon-txt" @click="setClickRuleFun(couponInfo.remarks)">规则 >></view>
						</view>
					</view>
					<view class="coupon-view-right absolute flex-all-center">
						<view class="view-right-rice">
							<text style="font-size: 40rpx;">￥</text>
							<text>{{ couponInfo.discount }}</text>
						</view>
					</view>
				</view>
				
				<view class="btn-coupon-box flex flex-justify-content-around" v-if="tabAreaList[tabCurrentIndex].type === 0">
					<!-- 取消 -->
					<view class="btn-coupon-bg relative" @click="isShowCouponPopup = false">
						<image class="bg" v-if="commonConfigs && commonConfigs.domainFrontFileLink"
						:src="`${commonConfigs.domainFrontFileLink}/files/images/coupons/cancel-btn.png`" 
						mode=""></image>
					</view>
					
					<!-- 确认兑换 -->
					<view class="btn-coupon-bg relative btn-coupon-bg2" @click="putChangeFun(couponInfo)" >
						<image class="bg" v-if="commonConfigs && commonConfigs.domainFrontFileLink"
						:src="`${commonConfigs.domainFrontFileLink}/files/images/coupons/sure-exchange-btn.png`" 
						mode=""></image>
					</view>
				</view>
				
				<view class="btn-coupon-box flex flex-justify-content-around" v-if="tabAreaList[tabCurrentIndex].type !== 0">
					<!-- #ifdef MP-WEIXIN -->
					<button open-type="share" class="button">
						<!-- 去赠送 -->
						<view class="btn-coupon-bg relative" v-if="couponInfo.status === 1">
							<image class="bg" v-if="commonConfigs && commonConfigs.domainFrontFileLink"
							:src="`${commonConfigs.domainFrontFileLink}/files/images/coupons/goto-give-btn.png`" 
							mode=""></image>
						</view>
						
						<!-- 重新赠送 -->
						<view class="btn-coupon-bg relative" v-else>
							<image class="bg" v-if="commonConfigs && commonConfigs.domainFrontFileLink"
							:src="`${commonConfigs.domainFrontFileLink}/files/images/coupons/re-give-btn.png`" 
							mode=""></image>
						</view>
					</button>
					<!-- #endif -->
					
					<!-- #ifdef APP-PLUS -->
					<button @click="setShareFun" class="button">
						<!-- 去赠送 -->
						<view class="btn-coupon-bg relative" v-if="couponInfo.status === 1">
							<image class="bg" v-if="commonConfigs && commonConfigs.domainFrontFileLink"
							:src="`${commonConfigs.domainFrontFileLink}/files/images/coupons/goto-give-btn.png`" 
							mode=""></image>
						</view>
						
						<!-- 重新赠送 -->
						<view class="btn-coupon-bg relative" v-else>
							<image class="bg" v-if="commonConfigs && commonConfigs.domainFrontFileLink"
							:src="`${commonConfigs.domainFrontFileLink}/files/images/coupons/re-give-btn.png`" 
							mode=""></image>
						</view>
					</button>
					<!-- #endif -->
				
					<!-- 去使用 -->
					<view class="btn-coupon-bg relative" @click="putGooUseFun(couponInfo)" v-if="couponInfo.status === 1">
						<image class="bg" v-if="commonConfigs && commonConfigs.domainFrontFileLink"
						:src="`${commonConfigs.domainFrontFileLink}/files/images/coupons/goto-use-btn.png`" 
						mode=""></image>
					</view>
					
					<!-- 取消赠送 -->
					<view class="btn-coupon-bg btn-coupon-bg2 relative" @click="setCancelGiftFun(couponInfo)" v-if="couponInfo.status === 5">
						<image class="bg" v-if="commonConfigs && commonConfigs.domainFrontFileLink"
						:src="`${commonConfigs.domainFrontFileLink}/files/images/coupons/cancel-give-btn.png`" 
						mode=""></image>
					</view>
				</view>
			</comOperCouponPopup>
			
			<comPromptPopup v-model="isShowUniq" title="优惠券口令" cancelText="关闭" confirmText="复制口令" @setSureFun="setCopyUniquFun">
				<view class="font-hanserif-bold flex-all-center" style="font-size: 48rpx;text-align: center;white-space: nowrap;color: #FFFFFF;">
					{{ UniqCodeTxt || '-' }}
				</view>
			</comPromptPopup>
			
			<comRuleUppop
				ruleName="优惠券规则"
				v-model="isShowRuleTxt"
				:isAllowedClickMaskClose="true">
				<template>
					<view v-html="remarkTxt"></view>
				</template>
			</comRuleUppop>
			
		</template>
	</comRoot>
</template>

<script>
	import { getCouponRowApi, getCouponPointsListApi, getCouponPointsConvertApi, getCouponHomeApi, getCouponDoneApi, getCouponShareApi, getCouponUnshareApi, getCouponReceiveApi } from '@/setupproject/INTERFACE.js';
	import pager from '@/inmixed/paging.mixin.js';
	import store from '@/store';
	import { ACTIONS } from '@/store/modules/userStore';
	import { setAsyncFunWait } from '@/setupproject/TOOLS_FUN';
	
	export default {
		name: 'couponInfoPage',
		mixins: [pager],
		data() {
			return {
				uniq: '',
				loading: false,
				tabCurrentIndex: 0,
				tabAreaList: [
					{ text: '可用卡券', type: 1 },
					{ text: '兑换卡券', type: 0 },
					{ text: '领取卡券', type: 3 },
					{ text: '赠送中', type: 5 },
					{ text: '已赠送', type: 4 },
					{ text: '历史卡券', type: 2 },
				],
				isShowRuleTxt: false,
				remarkTxt: '',
				isShowUniq: false,
				isReLoadData: false,
				shareEndFlag: false,
				UniqCodeTxt: '',
				isShowCouponPopup: false,
				couponInfo: {},
			};
		},

		watch: {
			async tabCurrentIndex(v) {
				this.resLists = [];
				// 领取
				if (this.tabAreaList[v].type === 3) {
					this.setReceiveCouponFun();
				} else if (this.tabAreaList[v].type === 0) {
					// 兑换
					this.setPointsCouponFun();
				} else {
					/* paging.mixin.js Methods */
					this.pagingInitFun();
					this.resListsGetFun();
				}
			},
			token: {
				handler(val, oldval) {
					if (val) {
						// 监听token，保证未登录的用户，自动登陆完触发领取优惠券接口
						setTimeout(async () => {
							console.log('execAfterToken');

							// 如果有优惠券ID，则触发领取接口
							if (this.uniq && this.token) {
								store.dispatch(ACTIONS.USER_INFO_GET_FUN);
								this.setCouponReceiveFun(this.uniq);
							}
						});
					}
				},
				immediate: true
			},
			
		},
		computed: {
			token() {
				return store.getters.token;
			},
			userInfo() {
				return this.$store.getters.userInfo;
			},
			commonNavHeight() {
				return store.getters.commonNavHeight + 'px';
			},
			commonConfigs() {
				return store.getters.commonConfigs || {};
			},
			showLoadendTxt() {
				return this.isShowPageLoadedTxt && !this.loading && this.resLists.length ? true : false;
			}
		},

		async onLoad(options) {
			this.uniq = options.uniq;
			if (options.uniq && this.token) {
				store.dispatch(ACTIONS.USER_INFO_GET_FUN);
				this.setCouponReceiveFun(options.uniq);
			}

			if (options.index) {
				this.tabCurrentIndex = +options.index;
			}
		},
		
		onShow() {
			if(this.isReLoadData) {
				this.shareEndFlag = false;
				this.isReLoadData = false;
				
				this.resLists = [];
				// 领取优惠券
				if (this.tabAreaList[this.tabCurrentIndex].type === 3) {
					this.setReceiveCouponFun();
				} else if (this.tabAreaList[this.tabCurrentIndex].type === 0) {
					// 兑换优惠券
					this.setPointsCouponFun();
				} else {
					/* paging.mixin.js Methods */
					this.pagingInitFun();
					this.resListsGetFun();
				}
			}
		},
		
		onHide() {
			if(this.shareEndFlag) {
				this.isReLoadData = true;
				this.isShowCouponPopup = false;
			}
		},
		
		onShareAppMessage(e) {
			this.shareEndFlag = true;
			
			uni.showLoading({
				title: '',
				mask: false
			});
			
			if (e.from === 'menu') {
				return this.$store.commit('SHARE_INFO_SET_FUN', {
					title: '旺卡抽赏实现你心中梦想!',
					path: `/pages/tabbar/tabbar?tabCurrentIndex=tabHome`,
					imageUrl: this.commonConfigs.domainFrontFileLink + '/files/images/common/new-mp-share.png',
					content: '',
					desc: ''
				});
			}
		
			const promise = new Promise(async (resolve) => {
				await this.setShareFun();
				const { shareObjData } = this.$store.getters;
				uni.hideLoading();
				await resolve(shareObjData);
			});
			
			return {
				promise
			};
		},
		
		methods: {
			async setChangeFun(item) {
				this.isShowCouponPopup = true;
				this.couponInfo = item;
			},
			
			async putChangeFun(item) {
				const {
					code,
					msg,
					data,
				} = await getCouponPointsConvertApi({
					coupon_id: item.id
				});
				
				uni.showToast({
					icon: code === 200 ? 'success' : 'none',
					title: data || msg,
				})
				
				await setAsyncFunWait(500);
				
				this.isShowCouponPopup = false;
				this.resLists = [];
				this.setPointsCouponFun();
			},
			
			async setShareFun() {
				let _this = this;
				const { userInfo } = this;
			
				const { data } = await getCouponShareApi({
					id: this.couponInfo.id
				});
			
				// #ifndef APP-PLUS
				await this.$store.commit('SHARE_INFO_SET_FUN', {
					title: `你的好友${this.userInfo.nickname || ''}送给你一张${this.couponInfo.titile}，快来一起抽赏吧~`,
					path: `/secondary/couponInfoPage/couponInfoPage?uniq=${data.uniq}`,
					imageUrl: this.commonConfigs.domainFrontFileLink + '/files/images/common/new-mp-share.png',
					content: '',
					desc: ''
				});
				// #endif
				
				// #ifdef APP-PLUS
				this.isShowUniq = true;
				this.UniqCodeTxt = data.uniq;
				this.resLists = [];
				
				/* paging.mixin.js Methods */
				this.pagingInitFun();
				this.resListsGetFun();
				// #endif
			},
			
			async listsGetFun() {
				this.loading = true;
				
				const { data, code } = await getCouponRowApi({
					page_size: this.pageInfoObj.page_size,
					page: this.pageInfoObj.page,
					type: this.tabAreaList[this.tabCurrentIndex].type,
				});
				
				this.loading = false;
				if (code !== 200) return false;
				data.resLists = data.list;
				this.isShowCouponPopup = false;
				
				return data;
			},
			
			putUseFun(item) {
				if (item.type === 1) {
					this.gooPageUrl(item);
				} else {
					this.isShowCouponPopup = true;
					this.couponInfo = item;
				}
			},

			putGooUseFun(item) {
				this.gooPageUrl(item);
			},
			
			async setCancelGiftFun(item) {
				const [em, modal] = await uni.showModal({
					content: '确定取消赠送？'
				});
			
				if (!modal.confirm) return;
			
				const { data, code, msg } = await getCouponUnshareApi({
					id: item.id
				});
			
				if (code !== 200) {
					return uni.showToast({
						icon: 'none',
						title: msg
					});
				}
				uni.showToast({
					icon: 'none',
					title: data
				});
				this.isShowCouponPopup = false;
				
				this.resLists = [];
				/* paging.mixin.js Methods */
				this.pagingInitFun();
				this.resListsGetFun();
			},
			
			async setReceiveCouponFun() {
				const resData = await getCouponHomeApi();
				this.resLists = resData.data;
			},
			
			setCopyUniquFun() {
				let _this = this;
				let UniqCodeTxt = this.UniqCodeTxt;
				uni.setClipboardData({
					data: UniqCodeTxt,
					success: async function () {
						uni.showToast({
							title: `已复制：${UniqCodeTxt}`,
							icon: 'none'
						});
						
						_this.isShowCouponPopup = false;
						_this.isShowUniq = false;
				
						_this.resLists = [];
						/* paging.mixin.js Methods */
						_this.pagingInitFun();
						_this.resListsGetFun();
					}
				});
			},
			
			async setCouponReceiveFun() {
				let uniq = this.uniq;
			
				const { code, msg } = await getCouponReceiveApi({
					uniq
				});
			
				this.uniq = '';
				if (code === 200) {
					const [em, modal] = await uni.showModal({
						title: '恭喜~',
						content: `您获得了优惠券`,
						confirmText: '确定',
						showCancel: false
					});
			
					if (!modal.confirm) return;
					
					await setAsyncFunWait(1000);
					await (this.resLists = []);
					
					/* paging.mixin.js Methods */
					await this.pagingInitFun();
					await this.resListsGetFun();
					return;
				} else {
					uni.showToast({
						title: msg,
						icon: 'error'
					});
				}
			},
			
			setClickRuleFun(remarks) {
				this.isShowRuleTxt = true;
				this.remarkTxt = remarks;
			},
			
			async setPointsCouponFun() {
				const resData = await getCouponPointsListApi();
				this.resLists = resData.data.coupon_config_list;
			},

			gooPageUrl(item) {
				if (item.reward_pool_id) {
					if (item.scene == 0) {
						return uni.redirectTo({
							url: `/pages/tabbar/tabbar?tabCurrentIndex=tabHome`
						});
					}
				} else {
					// 不限
					if (item.scene == 0) {
						return uni.redirectTo({
							url: `/pages/tabbar/tabbar?tabCurrentIndex=tabHome`
						});
					}
					// 跳转首页
					if (item.scene == 1) {
						return uni.redirectTo({
							url: `/pages/tabbar/tabbar?tabCurrentIndex=tabHome&scene=${item.scene}`
						});
					}
				}
			},

			
			// 一键领取
			async setAllReceiveFun() {
				if (this.resLists.length <= 0) return;

				const { data, code, msg } = await getCouponDoneApi();

				if (code === 200) {
					uni.showToast({
						icon: 'success',
						title: '领取成功'
					});
				}

				setTimeout(() => {
					this.setReceiveCouponFun();
					this.resLists = [];
					/* paging.mixin.js Methods */
					this.pagingInitFun();
					this.resListsGetFun();
				}, 300);
			},
		}
	};
</script>

<style lang="scss" scoped>
	.coupon-box-top {
		width: 700rpx;
		height: 90rpx;
		margin: 0 auto;
		.text {
			color: #FFFFFF;
			font-size: 26rpx;
		}
		.box-top-btn {
			text-align: center;
			color: #ffffff;
			font-size: 26rpx;
			background-size: 100% 100%;
			width: 129rpx;
			height: 49rpx;
			line-height: 49rpx;
		}
	}
	
	.coupon-content {
		width: 100%;
		color: #fff;
		margin-bottom: 18rpx;
		padding: 0rpx 22rpx 0rpx;
	
		.coupon-input {
			color: #8F4FFF;
			flex: 1 1 auto;
			border-radius: 12rpx;
			padding-left: 18rpx;
			height: 64rpx;
		}
	
		.coupon-receive-btn {
			width: 148rpx;
			height: 64rpx;
			margin-left: 18rpx;
		}
	}
	
	.tip-view-text {
		color: #FFFFFF;
		line-height: 50rpx;
		font-size: 26rpx;
		margin-top: 90rpx;
		background: linear-gradient(0deg, #FAFDC5 0%, #FFFFFF 100%);
		-webkit-background-clip: text;
		-webkit-text-fill-color: transparent;
	}
	
	.coupon-view {
		width: 590rpx;
		height: 210rpx;
		align-items: center;
		padding-left: 32rpx;
		font-size: 24rpx;
		flex: 0 0 auto;
		color: #FFFFFF;
		background-size: 100% 100%;
		.coupon-view-left {
			width: 100%;
			font-size: 20rpx;
			.view-left-sub-title {
				font-size: 48rpx;
				margin-bottom: 20rpx;
				margin-top: 12rpx;
				font-weight: bold;
				color: #FFFFFF;
			}
			.view-left-bottom {
				font-size: 22rpx;
				.coupon-txt {
					margin-left: 38rpx;
					color: #63FFF7;
				}
			}
		}
		.coupon-view-right {
			right: 18px;
			top: 60rpx;
			.check {
				right: -10rpx;
				width: 31rpx;
				height: 30rpx;
				align-self: flex-end;
				left: -4rpx;
			}
			.view-right-rice {
				text-align: center;
				font-size: 60rpx;
				color: #63FFF7;
			}
		}
	}
	
	.btn-coupon-box {
		bottom: -100rpx;
		width: 100%;
		position: absolute;
		.btn-coupon-bg {
			text-align: center;
			background-size: 100% 100%;
			width: 176rpx;
			height: 60rpx;
			line-height: 60rpx;
		}
		.btn-coupon-bg2 {
			background-size: 100% 100%;
		}
	}
</style>
